<?php
namespace plugin\ai_invitation\app\middleware;

use plugin\ai_invitation\api\Invitation;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class LoginControl implements MiddlewareInterface
{
    /**
     * @param Request $request
     * @param callable $handler
     * @return Response
     */
    public function process(Request $request, callable $handler): Response
    {
        $platformEnable = config('plugin.sns.wechat.platform.enable');
        $response = $handler($request);
        if ($platformEnable){
            $response->withBody($this->modifyHtml($response->rawBody()));
        }
        return $response;
    }

    private function modifyHtml($html): string
    {
        $setting = Invitation::getSetting();
        $origin = [
            '</form>',
            '</style>'
        ];
        $otherLoginHtml = <<<EOF
<div class="other-login">
                <div class="title-warp d-flex justify-content-between mb-3">
                    <div class="line text-secondary"></div>
                    <div class="title">其他方式登录</div>
                    <div class="line text-secondary"></div>
                </div>
                <div class="other-login-list d-flex justify-content-around">
                    <a href="
EOF;
        $otherLoginHtml .= $setting['platform']['auth_url'];
        $otherLoginHtml .= <<<EOF
" style="line-height: 1;">
                        <svg class="icon" aria-hidden="true" id="weixin">
                            <use xlink:href="#icon-weixin"></use>
                        </svg>
                    </a>
                </div>
            </div>
        </form>
EOF;
        $newHtml = [
            $otherLoginHtml,
            <<<EOF
    /* sns插件样式 */
    .other-login .title-warp {
        align-items: center;
    }
    .other-login .title-warp .title{
        color: rgba(0,0,0,.5);
    }
    .other-login .title-warp .line {
        box-sizing: border-box;
        margin: 0;
        min-width: 0;
        border-top: 1px solid;
        width: 120px
    }
    .other-login .other-login-list{
        font-size: 38px;
    }
    .other-login .icon {
        width: 1em;
        height: 1em;
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
    }
</style>
<script src="/app/sns/js/sns-iconfont.js"></script>
EOF
        ];
        return str_replace($origin,$newHtml,$html);
    }

}
